//
//  RSearchViewController.m
//  iPlan
//
//  Created by 侯伟 on 2021/8/24.
//

#import "RSearchViewController.h"
#import "RSRefreshTableView.h"
#import "RSearchVideoTableViewCell.h"
#import "SearchBar.h"
#import "IFMMenu.h"
#import "SearchRequest.h"
#import "HotKewordRequest.h"
#import "HistoryWords.h"
#import "RVideoObj.h"

#import "RVideoDetailsViewController.h"

static NSString* nameCellIdentifier = @"nameCell";

@interface RSearchViewController ()<SearchBarDelegate,RSRefreshTableViewDelegate,UITableViewDelegate,UITableViewDataSource>{
    
    ///搜索关键字
    NSString* _keywords;
    /// 演员/片名
    SearchType _searchType;
}


//0.不搜索 1.模糊搜索 2.精准搜索
@property(nonatomic,assign)NSInteger searchIndex;


@property(nonatomic,strong)SearchBar* searchBar;

/// 影片
@property(nonatomic,strong)RSRefreshTableView* tableView;

/// 历史
@property(nonatomic,strong)MyLinearLayout* historyView;


@property(nonatomic,strong)MyLinearLayout* historyLayout;

// 搜索历史 流式布局
@property(nonatomic,strong)MyFlowLayout* historyContentLayout;


@property(nonatomic,strong)MyLinearLayout* hotLayout;

// 热门推荐 流式布局
@property(nonatomic,strong)MyFlowLayout* hotContentLayout;


@property(nonatomic,strong)NSArray* hots;


@property(nonatomic,strong)RLMResults* historys;

@end

@implementation RSearchViewController

- (void)loadView{
    [super loadView];
    // 线性布局
    MyRelativeLayout *rootLayout = [MyRelativeLayout new];
    rootLayout.insetsPaddingFromSafeArea = UIRectEdgeLeft|UIRectEdgeRight;
    rootLayout.backgroundColor = UIColor.whiteColor;
    self.view = rootLayout;
}

- (instancetype)init{
    if(self = [super init]){
        _searchType = SearchType_Video;
        _searchIndex = -1;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.navigationItem setHidesBackButton:YES];
    
    [self setupSearchBar];
    
    [self setupHistoryView];
    
    [self setupTableView];
    
    [self readHistory];
    
    [self requestHot];
    
    self.searchIndex = 0;
}

- (void)setupSearchBar{
    SearchBar* searchBar = [SearchBar new];
    searchBar.delegate = self;
    searchBar.frame = CGRectMake(0, 0, SCREEN_WIDTH, 44);
    searchBar.myMargin = 0;
    self.navigationItem.titleView = searchBar;
    _searchBar = searchBar;
}

- (void)setupHistoryView{
    
    UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:self.view.bounds];
    scrollView.showsHorizontalScrollIndicator = NO;
    scrollView.showsVerticalScrollIndicator = NO;
    scrollView.myMargin = 0;
    [self.view addSubview:scrollView];
    
    MyLinearLayout* historyView = [MyLinearLayout linearLayoutWithOrientation:(MyOrientation_Vert)];
    historyView.myHorzMargin = 0;
    historyView.myTop = 0;
    historyView.heightSize.lBound(scrollView.heightSize, 10, 1);
    [scrollView addSubview:historyView];
    _historyView = historyView;
    
    MyLinearLayout* historyLayout = [MyLinearLayout linearLayoutWithOrientation:(MyOrientation_Vert)];
    historyLayout.myHeight = MyLayoutSize.wrap;
    historyLayout.myMargin = 0;
    historyLayout.padding = UIEdgeInsetsMake(16, 16, 16, 16);
    [historyView addSubview:historyLayout];
    _historyLayout = historyLayout;
    
    MyLinearLayout* historyTitleLayout = [MyLinearLayout linearLayoutWithOrientation:(MyOrientation_Horz)];
    historyTitleLayout.myHeight = MyLayoutSize.wrap;
    historyTitleLayout.gravity = MyGravity_Horz_Between;
    historyTitleLayout.myMargin = 0;
    [historyLayout addSubview:historyTitleLayout];
    
    UILabel* historyTitleLb = [UILabel lableWithFont:FONTMID_FIT(15) color:COLOR_BLACK_DARK text:@"历史纪录"];
    historyTitleLb.myMargin = 0;
    [historyTitleLayout addSubview:historyTitleLb];
    
    UIButton* trashBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
    [trashBtn setImage:[UIImage imageNamed:@"common_trash"] forState:UIControlStateNormal];
    [trashBtn addTarget:self action:@selector(clearHistory:) forControlEvents:UIControlEventTouchUpInside];
    trashBtn.myMargin = 0;
    trashBtn.mySize = CGSizeMake(PX(30), PX(30));
    [historyTitleLayout addSubview:trashBtn];

    // 流式布局
    MyFlowLayout* historyContentLayout = [MyFlowLayout flowLayoutWithOrientation:MyOrientation_Vert arrangedCount:0];
    historyContentLayout.myHeight = MyLayoutSize.wrap;
    historyContentLayout.subviewSpace = 16;
    historyContentLayout.padding = UIEdgeInsetsMake(8, 0, 8, 0);
    historyContentLayout.myMargin = 0;
    historyContentLayout.autoArrange = YES;
    [historyLayout addSubview:historyContentLayout];
    _historyContentLayout = historyContentLayout;
    

    MyLinearLayout* hotLayout = [MyLinearLayout linearLayoutWithOrientation:(MyOrientation_Vert)];
    hotLayout.myHeight = MyLayoutSize.wrap;
    hotLayout.myMargin = 0;
    hotLayout.padding = UIEdgeInsetsMake(8, 16, 16, 16);
    hotLayout.subviewVSpace = 10;
    [historyView addSubview:hotLayout];
    _hotLayout = hotLayout;

    UILabel* hotTitleLb = [UILabel lableWithFont:FONTMID_FIT(15) color:COLOR_BLACK_DARK text:@"热门搜索"];
    hotTitleLb.myMargin = 0;
    [hotLayout addSubview:hotTitleLb];

    // 流式布局
    MyFlowLayout* hotContentLayout = [MyFlowLayout flowLayoutWithOrientation:MyOrientation_Vert arrangedCount:2];
    hotContentLayout.myHeight = MyLayoutSize.wrap;
    hotContentLayout.gravity = MyGravity_Horz_Fill;
    hotContentLayout.subviewHSpace = 8;
    hotContentLayout.subviewVSpace = 16;
    hotContentLayout.padding = UIEdgeInsetsMake(8, 0, 8, 0);
    hotContentLayout.myMargin = 0;
    [hotLayout addSubview:hotContentLayout];
    _hotContentLayout = hotContentLayout;
}

-(void)setupTableView{
    
    //列表
    RSRefreshTableView* tableView = [[RSRefreshTableView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), SCREEN_HEIGHT - IPHONE_NAVIGATION_BAR_HEIGHT) style:UITableViewStylePlain];
    tableView.refreshEnabled = YES;
    tableView.loadMoreEnabled = YES;
    tableView.refreshDelegate = self;
    
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.backgroundColor = UIColor.whiteColor;
    tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    [tableView registerClass:NSClassFromString(searchMovieCell) forCellReuseIdentifier:searchMovieCell];
    [tableView registerClass:UITableViewCell.class forCellReuseIdentifier:nameCellIdentifier];
    tableView.myMargin = 0;
    [self.view addSubview:tableView];
    _tableView = tableView;

}

//创建历史搜索影片item
- (void)setupHistoryItems{
    
    [self.historyContentLayout removeAllSubviews];
    
    for (int i = 0; i < self.historys.count; i++) {
        HistoryWords* keyword = [self.historys objectAtIndex:i];
        
        UIButton *tagButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
        [tagButton setTitle:keyword.keyword forState:UIControlStateNormal];
        [tagButton setTitleColor:COLOR_GRAY_BASE forState:UIControlStateNormal];
        tagButton.titleLabel.font = FONT_FIT(12);
        tagButton.backgroundColor = COLOR_BACKGEOUND;
        tagButton.layer.cornerRadius = 9;
        tagButton.widthSize.equalTo(@(MyLayoutSize.wrap)).add(16).min(PX(40));
        tagButton.heightSize.equalTo(@(PX(18)));
        tagButton.tag = 100+i;
        [tagButton sizeToFit];
        [tagButton addTarget:self action:@selector(handleHistoryTag:) forControlEvents:UIControlEventTouchUpInside];
        [self.historyContentLayout addSubview:tagButton];
    }
}

// //创建热门影片item
- (void)setupHotItems{
    
    for (int i = 0 ; i <self.hots.count ; i++) {
        HotKeyword* hot = self.hots[i];
        
        MyLinearLayout* hotItem = [MyLinearLayout linearLayoutWithOrientation:(MyOrientation_Horz)];
        hotItem.tag = 100+i;
        [hotItem setTarget:self action:@selector(handleHotTag:)];
        hotItem.heightSize.equalTo(@(PX(18)));
        hotItem.subviewHSpace = 10;
        hotItem.myMargin = 0;
        
        UIColor* bgColor = COLOR_GRAY_QUITE;
        if(i == 0){
            bgColor = COLOR_RED;
        }else if (i == 1){
            bgColor = COLOR_ORANGE;
        }else if (i == 2){
            bgColor = COLOR_BLUE;

        }
        UILabel* rankLb = [UILabel lableWithFont:FONT_FIT(12) color:COLOR_WHITE text:[NSString stringWithFormat:@"%d",i+1]];
        rankLb.backgroundColor = bgColor;
        rankLb.textAlignment = NSTextAlignmentCenter;
        rankLb.layer.cornerRadius = 2;
        rankLb.layer.masksToBounds = YES;
        rankLb.mySize = CGSizeMake(PX(18), PX(18));
        rankLb.myMargin = 0;
        [hotItem addSubview:rankLb];
        
        UILabel* titleLb = [UILabel lableWithFont:FONT_FIT(12) color:COLOR_GRAY_BASE text:hot.name];
        titleLb.myMargin = 0;
        titleLb.weight = 1.0;
        [hotItem addSubview:titleLb];
        
        [self.hotContentLayout addSubview:hotItem];
    }
}

- (void)setSearchIndex:(NSInteger)searchIndex{
    
    if(_searchIndex == searchIndex) return;
    
    _searchIndex = searchIndex;
    
    if(0 == searchIndex){
        self.historyView.visibility = MyVisibility_Visible;
        self.tableView.visibility = MyVisibility_Gone;
    }else{
        self.historyView.visibility = MyVisibility_Gone;
        self.tableView.visibility = MyVisibility_Visible;
    }
    
    [self.tableView updateData:@[] refreshType:Refresh isSuccess:YES];
}




#pragma mark  -- request
//搜搜视频
- (void)requestData:(RefreshType)refreshType{
    
    if(!_keywords.length){
        [self.tableView updateData:@[] refreshType:refreshType isSuccess:YES];
        return;
    }
    
    NSUInteger pageIndex = refreshType == Refresh?1:self.tableView.pageIndex+1;
    
    SearchRequest* request = [SearchRequest new];
    request.action = @"s";
    request.key_word = _keywords;
    request.type = _searchType;
    request.page = pageIndex;
    [RequestOperation encryptedRequest:request quite:YES callBack:^(HResponse * _Nullable response) {
        [[response success:^(SearMoviesList*  _Nonnull data) {
            self.tableView.total = data.total;
            self.tableView.pageIndex = data.current_page;
            
            [self.tableView updateData:data.lists refreshType:refreshType isSuccess:YES];
        }] failure:^(APIError * _Nonnull error) {
            [self.tableView updateData:@[] refreshType:refreshType isSuccess:NO];
        }];
    }];
}

//去取历史搜索
- (void)readHistory{
    
    
    RLMResults* historys = [HistoryWords allObjects];
    self.historys = [historys sortedResultsUsingKeyPath:@"timeStamp" ascending:NO];
    
    [self setupHistoryItems];
}

//热门
- (void)requestHot{
    
    [self.hotContentLayout removeAllSubviews];
    
    HotKewordRequest* request = [HotKewordRequest new];
    request.action = @"h_s";
    
    [RequestOperation encryptedRequest:request quite:YES callBack:^(HResponse * _Nullable response) {
        [[response success:^(NSArray*  _Nonnull data) {
            
            self.hots = data;
            [self.hotContentLayout removeAllSubviews];
            
            self.hotLayout.visibility = MyVisibility_Visible;
            
            [self setupHotItems];
            
        }] failure:^(APIError * _Nonnull error) {
            self.hots = @[];
            [self.hotContentLayout removeAllSubviews];
            
            self.hotLayout.visibility = MyVisibility_Gone;
        }];
    }];
}
#pragma mark -- action
- (void)handleHistoryTag:(UIButton*)sender{
    self.searchIndex = 2;//点击历史 进行精准搜索
    
    NSInteger index = sender.tag - 100;
    HistoryWords* word = [self.historys objectAtIndex:index];
    self.searchBar.searchWord = word.keyword;
    
    _keywords = word.keyword;
    
    [self requestData:Refresh];
    
    
    [[RLMRealm defaultRealm] beginWriteTransaction];
    word.timeStamp = [[NSDate date] timeIntervalSince1970];
    [[RLMRealm defaultRealm] addOrUpdateObject:word];
    [[RLMRealm defaultRealm] commitWriteTransaction];
    
    [self readHistory];
}

- (void)handleHotTag:(UIButton*)sender{
    
    self.searchIndex = 2;//点击热门 进行精准搜索
    
    NSInteger index = sender.tag - 100;
    HotKeyword* keyword = [self.hots objectAtIndex:index];
    self.searchBar.searchWord = keyword.name;
    
    _keywords = keyword.name;
    
    [self requestData:Refresh];
    
    HistoryWords* history = [HistoryWords new];
    history.keyword = keyword.name;
    history.timeStamp = [[NSDate date] timeIntervalSince1970];
    
    [[RLMRealm defaultRealm] beginWriteTransaction];
    [[RLMRealm defaultRealm] addOrUpdateObject:history];
    [[RLMRealm defaultRealm] commitWriteTransaction];
    
    [self readHistory];
    
}

- (void)clearHistory:(UIButton*)sender{
    
    [HistoryWords allObjects];
    
    // 获取 Student 模型的所有数据
    RLMResults *results = [HistoryWords allObjects];
    RLMRealm *realm = [RLMRealm defaultRealm];
    // 在事务里面删除模型里面的所有数据
    [realm transactionWithBlock:^{
        [realm deleteObjects:results];
    }];
    
    [self readHistory];
}

#pragma mark --UITableViewDelegate  UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.tableView.datas.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(1 == self.searchIndex){
        return PX(44);
    }
    return PX(157)+16;
}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell* cell;
    RVideoObj* movie = self.tableView.datas[indexPath.row];
    if(1 == self.searchIndex){
        UITableViewCell* nameCell = [tableView dequeueReusableCellWithIdentifier:nameCellIdentifier forIndexPath:indexPath];
        nameCell.textLabel.font = FONT_FIT(14);
        nameCell.textLabel.textColor = COLOR_BLACK_DARK;
        
        NSMutableAttributedString* attrText = [[NSMutableAttributedString alloc] initWithString:movie.name?movie.name:@""];
        [attrText addAttributes:@{NSForegroundColorAttributeName:COLOR_ORANGE} range:[movie.name rangeOfString:_keywords]];
        nameCell.textLabel.attributedText = attrText;
        cell = nameCell;
    }else{
        RSearchVideoTableViewCell* movieCell = [tableView dequeueReusableCellWithIdentifier:searchMovieCell forIndexPath:indexPath];
        movieCell.movie = movie;
        cell = movieCell;
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    RVideoObj* video = self.tableView.datas[indexPath.row];
    
    if(1 == self.searchIndex){
        self.searchIndex = 2;
        
        self.searchBar.searchWord = video.name;
        _keywords = video.name;
        
        if(_searchType == SearchType_Performer){
            _searchType = SearchType_Video;
            self.searchBar.searchType = SearchType_Video;
        }
        
        [self.tableView updateData:@[] refreshType:Refresh isSuccess:YES];
        
        [self requestData:Refresh];
        
        HistoryWords* history = [HistoryWords new];
        history.keyword = video.name;
        history.timeStamp = [[NSDate date] timeIntervalSince1970];
        
        [[RLMRealm defaultRealm] beginWriteTransaction];
        [[RLMRealm defaultRealm] addOrUpdateObject:history];
        [[RLMRealm defaultRealm] commitWriteTransaction];
        [self readHistory];
        
    }else{
        /// To Details
        RVideoDetailsViewController* details = [RVideoDetailsViewController new];
        details.video = video;
        [UIViewController showViewController:details animated:YES];
    }
}

#pragma mark  --RSRefreshTableViewDelegate

- (void)tableView:(RSRefreshTableView *)tableView refreshType:(RefreshType)refreshType{
    [self requestData:refreshType];
}


#pragma mark  -- SearchBarDelegate;

- (void)searchBar:(SearchBar *)searchBar textDidChange:(NSString *)searchWord{
    if(searchWord.length){
        if(self.searchIndex != 1)
            self.searchIndex = 1;
        
        _keywords = searchWord;
        
        [self requestData:Refresh];
    }else{
        if(self.searchIndex != 0)
            self.searchIndex = 0;
        
        _keywords = searchWord;
    }
}

- (void)searchBarCancelButtonClicked:(SearchBar *)searchBar{
    [self closeViewControllerAnimated:YES];
}

- (void)searchBar:(SearchBar *)searchBar typeDidChange:(SearchType)type{
    _searchType = type;
    self.searchIndex = 1;
    [self requestData:Refresh];
}
@end
